package com.itheima.restkeeper.face;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.restkeeper.AffixFace;
import com.itheima.restkeeper.UserFace;
import com.itheima.restkeeper.enums.UserEnum;
import com.itheima.restkeeper.exception.ProjectException;
import com.itheima.restkeeper.pojo.Resource;
import com.itheima.restkeeper.pojo.Role;
import com.itheima.restkeeper.pojo.User;
import com.itheima.restkeeper.req.AffixVo;
import com.itheima.restkeeper.req.BrandVo;
import com.itheima.restkeeper.req.UserVo;
import com.itheima.restkeeper.service.IUserAdapterService;
import com.itheima.restkeeper.service.IUserService;
import com.itheima.restkeeper.utils.BeanConv;
import com.itheima.restkeeper.utils.EmptyUtil;
import com.itheima.restkeeper.utils.ExceptionsUtil;
import com.itheima.restkeeper.utils.ResponseWrapBuild;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Method;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName UserFaceImpl.java
 * @Description 用户dubbo服务实现
 */
@Slf4j
@DubboService(version = "${dubbo.application.version}",timeout = 5000,
    methods ={
        @Method(name = "findUserVoPage",retries = 2),
        @Method(name = "createUser",retries = 0),
        @Method(name = "updateUser",retries = 0),
        @Method(name = "deleteUser",retries = 0)
    })
public class UserFaceImpl implements UserFace {

    @DubboReference(version = "${dubbo.application.version}",check = false)
    AffixFace affixFace;

    @Autowired
    IUserService userService;

    @Autowired
    IUserAdapterService userAdapterService;

    @Override
    public Page<UserVo> findUserVoPage(UserVo userVo,
                                       int pageNum,
                                       int pageSize)throws ProjectException {
        try {
            //查询用户分页
            Page<User> userVoPage = userService.findUserVoPage(userVo, pageNum, pageSize);
            Page<UserVo> page = new Page<>();
            BeanConv.toBean(userVoPage,page);
            List<UserVo> userVoList = page.getRecords();
            BeanConv.toBeanList(userVoList,UserVo.class);
            //结果集转换
            if (!EmptyUtil.isNullOrEmpty(page)&&!EmptyUtil.isNullOrEmpty(userVoList)) {
                //处理附件
                userVoList.forEach(n -> {
                    List<AffixVo> affixVoList = affixFace.findAffixVoByBusinessId(n.getId());
                    if (!EmptyUtil.isNullOrEmpty(affixVoList)) {
                        n.setAffixVo(affixVoList.get(0));
                    }
                    //处理角色
                    List<Role> roleVo = userAdapterService.findRoleByUserId(n.getId());
                    ArrayList<String> roleList = new ArrayList<>();
                    for (Role role : roleVo) {
                        roleList.add(String.valueOf(role.getId()));
                    }
                    String[] roleId = new String[(roleList.size())];
                    roleList.toArray(roleId);
                    n.setHasRoleIds(roleId);
                });
                page.setRecords(userVoList);
            }
            //返回结果
            return page;
        } catch (Exception e) {
            log.error("查询用户列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.PAGE_FAIL);
        }
    }

    @Override
    public UserVo createUser(UserVo userVo)throws ProjectException {
        try {
            //保存用户
            UserVo userResult = BeanConv.toBean(userService.createUser(userVo), UserVo.class);
            if (!EmptyUtil.isNullOrEmpty(userResult)) {
                //绑定附件
                affixFace.bindBusinessId(
                        AffixVo.builder()
                                .businessId(userResult.getId())
                                .id(userVo.getAffixVo().getBusinessId())
                                .build()
                );
                userResult.setAffixVo(
                        AffixVo.builder()
                                .pathUrl(userVo.getAffixVo().getPathUrl())
                                .businessId(userResult.getId())
                                .id(userVo.getAffixVo().getId()).build()
                );
                //处理角色
                userResult.setHasRoleIds(userVo.getHasRoleIds());
            }
            return userResult;
        } catch (Exception e) {
            log.error("保存用户异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.CREATE_FAIL);
        }
    }

    @Override
    public Boolean updateUser(UserVo userVo) throws ProjectException{
        try {
            //修改用户
            Boolean flag = userService.updateUser(userVo);
            if (flag) {
                List<AffixVo> BusinessId = affixFace.findAffixVoByBusinessId(userVo.getId());
                //删除图片
                List<Long> collect = BusinessId.stream().map(AffixVo::getId).collect(Collectors.toList());
                if (!collect.contains(userVo.getAffixVo().getId())) {
                    //绑定新图
                    affixFace.deleteAffixVoByBusinessId(userVo.getId());

                    affixFace.bindBusinessId(
                            AffixVo.builder()
                                    .businessId(userVo.getId())
                                    .id(userVo.getAffixVo().getId()).build()
                    );
                }
            }
            return flag;
        } catch (Exception e) {
            log.error("保存用户异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.UPDATE_FAIL);
        }
    }

    @Override
    public Boolean deleteUser(java.lang.String[] checkedIds) throws ProjectException {
        try {
            //删除用户
            Boolean flag = userService.deleteUser(checkedIds);
            //删除图片
            for (String checkedId : checkedIds) {
                affixFace.deleteAffixVoByBusinessId(Long.valueOf(checkedId));
            }
            return flag;
        } catch (Exception e) {
            log.error("删除用户异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.DELETE_FAIL);
        }
    }


    @Override
    public UserVo findUserByUserId(Long userId)throws ProjectException {
        try {
            //查找用户
            User user = userService.getById(userId);
            UserVo userVo = BeanConv.toBean(user, UserVo.class);
            if (!EmptyUtil.isNullOrEmpty(user)){
                //处理附件
                List<AffixVo> affixVoList = affixFace.findAffixVoByBusinessId(user.getId());
                if (!EmptyUtil.isNullOrEmpty(affixVoList)) {
                    userVo.setAffixVo(affixVoList.get(0));
                }
                return userVo;
            }
            return null;
        } catch (Exception e) {
            log.error("查找用户所有角色异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.SELECT_USER_FAIL);
        }
    }

    @Override
    public List<UserVo> findUserVoList()throws ProjectException {
        try {
            //查找用户下拉框
            return BeanConv.toBeanList(userService.findUserVoList(), UserVo.class);
        } catch (Exception e) {
            log.error("查找用户list异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(UserEnum.SELECT_USER_LIST_FAIL);
        }
    }
}
